package com.lenovo.smarttraffic.ui.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lenovo.smarttraffic.Constant;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.api.VolleyCallBack;
import com.lenovo.smarttraffic.bean.GsonBean.MetroInfoBean;
import com.lenovo.smarttraffic.bean.MetroDialogEventBusBean;
import com.lenovo.smarttraffic.bean.MetroResultBean;
import com.lenovo.smarttraffic.ui.fragment.MetroLineFragment;
import com.lenovo.smarttraffic.ui.fragment.MetroRecyclerFragment;
import com.lenovo.smarttraffic.util.VolleyUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by Caleb.F
 * on 2019-11-24
 * at 21:54
 */
public class MetroSearchActivity extends BaseActivity implements View.OnClickListener {
    private static final Integer SHOW_ACTIVITY = 0;
    private static final Integer SHOW_DIALOG = 1;

    private static final String METRO_LINE_FRAGMENT = "com.lenovo.smarttraffic.ui.fragment.MetroLineFragment";
    private static final String METRO_RECYCLER_FRAGMENT = "com.lenovo.smarttraffic.ui.fragment.MetroRecyclerFragment";

    private Button mBtnLine1;
    private Button mBtnLine2;
    private Button mBtnLine3;
    private Button mBtnLine4;
    private Button mBtnLine10;
    private Button mBtnLineS1;
    private Button mBtnLineS3;
    private Button mBtnLineS8;

    private Button mButton11;
    private EditText mEdStartPort;
    private EditText mEdEndSpot;


    private MetroInfoBean metroInfoBean;
    private ProgressDialog mProgressDialog;
    private FragmentManager mManager;
    //线对应的换乘站点
    private HashMap<String, List<String>> transforSitesMap;
    //换乘站点对应的线
    private HashMap<String, List<String>> transforLineMap;
    //线对应的所有站点
    private HashMap<String, List<String>> allSpotMap;
    private String firstLocation;
    private String lastLocation;
    private MetroRecyclerFragment metroRecyclerFragment;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mProgressDialog = new ProgressDialog(this);
        initview();
        allSpotMap = new HashMap<>();
        transforSitesMap = new HashMap<>();
        transforLineMap = new HashMap<>();
    }


    private void initview() {
        initToolBar("地铁站点选择");
        mBtnLine1 = findViewById(R.id.btn_line1);
        mBtnLine2 = findViewById(R.id.btn_line2);
        mBtnLine3 = findViewById(R.id.btn_line3);
        mBtnLine4 = findViewById(R.id.btn_line4);
        mBtnLine10 = findViewById(R.id.btn_line10);
        mBtnLineS1 = findViewById(R.id.btn_line_s1);
        mBtnLineS3 = findViewById(R.id.btn_line_s3);
        mBtnLineS8 = findViewById(R.id.btn_line_s8);
        mButton11 = findViewById(R.id.button11);
        final Button[] buttons = new Button[]{
                mBtnLine1, mBtnLine2, mBtnLine3, mBtnLine4, mBtnLine10, mBtnLineS1, mBtnLineS3, mBtnLineS8, mButton11
        };
        for (int i = 0; i < buttons.length; i++) {
            buttons[i].setOnClickListener(this);
        }
        mEdEndSpot = findViewById(R.id.ed_end_spot);
        mEdStartPort = findViewById(R.id.ed_start_port);
        mEdEndSpot.setOnClickListener(this);
        mEdStartPort.setOnClickListener(this);

    }

    @Override
    protected int getLayout() {
        return R.layout.activity_metro_search;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_line1:
                SearchMetroLine(1, SHOW_ACTIVITY);
                break;
            case R.id.btn_line2:
                SearchMetroLine(2, SHOW_ACTIVITY);
                break;
            case R.id.btn_line3:
                SearchMetroLine(3, SHOW_ACTIVITY);
                break;
            case R.id.btn_line4:
                SearchMetroLine(5, SHOW_ACTIVITY);
                break;
            case R.id.btn_line10:
                SearchMetroLine(6, SHOW_ACTIVITY);
                break;
            case R.id.btn_line_s1:
                SearchMetroLine(4, SHOW_ACTIVITY);
                break;
            case R.id.btn_line_s3:
                SearchMetroLine(8, SHOW_ACTIVITY);
                break;
            case R.id.btn_line_s8:
                SearchMetroLine(7, SHOW_ACTIVITY);
                break;
            case R.id.button11:
                if (TextUtils.isEmpty(mEdEndSpot.getText()) || TextUtils.isEmpty(mEdStartPort.getText())) {
                    mButton11.setEnabled(false);
                    mButton11.setBackgroundResource(R.drawable.btn_line_search);
                } else {
                    Toast.makeText(this, "路线查询已完成", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(MetroSearchActivity.this, MetroResultActivity.class);
                    intent.putExtra(Constant.METRO_START_SPOT, mEdStartPort.getText().toString());
                    intent.putExtra(Constant.METRO_END_SPOT, mEdEndSpot.getText().toString());
                    startActivity(intent);
                }
                break;
            case R.id.ed_start_port:
                chooseMetroLine(Constant.METRO_FIRST_LOCATION);
                break;
            case R.id.ed_end_spot:
                chooseMetroLine(Constant.METRO_LAST_LOCATION);
                break;
        }

    }

    /**
     * @param LocationType 起点还是终点选择
     */
    private void chooseMetroLine(String LocationType) {
        mManager = this.getSupportFragmentManager();
        MetroLineFragment metroLineFragment = new MetroLineFragment();
        mManager.beginTransaction().add(metroLineFragment, METRO_LINE_FRAGMENT).commit();
        metroLineFragment.setOnItemClickListener(metroLineName -> {
            if (transforSitesMap.isEmpty()) {
                getAllMetroLine();
            }
            getMetroLine(metroLineName);
            metroLineFragment.dismiss();

            showrecyclerDialog(LocationType);
        });
    }

    /**
     * @param LocationType 展示reycyclerdialog
     */
    private void showrecyclerDialog(String LocationType) {
        metroRecyclerFragment = new MetroRecyclerFragment();
        Bundle bundle = new Bundle();
        //起点和终点的选择服用的代码
        bundle.putString(Constant.METRO_LOCATION_TYPE, LocationType);
        metroRecyclerFragment.setArguments(bundle);
        mManager.beginTransaction().add(metroRecyclerFragment, METRO_RECYCLER_FRAGMENT).commit();
        metroRecyclerFragment.serOnLocationListener(new MetroRecyclerFragment.onLocationSelectListener() {
            @Override
            public void onFirstLocationSelect(String s) {
                firstLocation = s;
                checkLocation();
            }
            @Override
            public void onLastLocationSelect(String s) {
                lastLocation = s;
                checkLocation();
            }
        });
    }

    /**
     * editText站点选择，不可重复
     */
    private void checkLocation() {
        mButton11.setEnabled(false);
        mButton11.setBackgroundResource(R.drawable.btn_line_search);
        if (lastLocation == null && firstLocation != null) {
            mEdStartPort.setText(firstLocation);
            metroRecyclerFragment.dismiss();
        } else if (firstLocation == null && lastLocation != null) {
            mEdEndSpot.setText(lastLocation);
            metroRecyclerFragment.dismiss();
        } else if (firstLocation != null && lastLocation != null) {
            if (firstLocation.equals(lastLocation)) {
                Toast.makeText(this, "不可选择重复站点,请重新选择", Toast.LENGTH_SHORT).show();
            } else {
                mEdStartPort.setText(firstLocation);
                mEdEndSpot.setText(lastLocation);
                metroRecyclerFragment.dismiss();
                mButton11.setEnabled(true);
                mButton11.setBackgroundResource(R.drawable.btn_line_search_enable);
            }
        }
    }

    private void getMetroLine(String metroLineName) {
        int metroValue;
        switch (metroLineName) {
            case "4":
                metroValue = 5;
                SearchMetroLine(metroValue, SHOW_DIALOG);
                break;
            case "10":
                metroValue = 6;
                SearchMetroLine(metroValue, SHOW_DIALOG);
                break;
            case "s1":
                metroValue = 4;
                SearchMetroLine(metroValue, SHOW_DIALOG);
                break;
            case "s3":
                metroValue = 8;
                SearchMetroLine(metroValue, SHOW_DIALOG);
                break;
            case "s8":
                metroValue = 7;
                SearchMetroLine(metroValue, SHOW_DIALOG);
                break;
            default:
                metroValue = Integer.valueOf(metroLineName);
                SearchMetroLine(metroValue, SHOW_DIALOG);
                break;
        }

    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    //传入展示activity的数据
                    EventBus.getDefault().postSticky(metroInfoBean);
                    startActivity(new Intent(MetroSearchActivity.this, MetroLineActivity.class));
                    break;
                case 2:
                    //传入展示dialog的数据
                    EventBus.getDefault().postSticky(new MetroDialogEventBusBean(metroInfoBean, transforLineMap));
                    EventBus.getDefault().postSticky(new MetroResultBean(allSpotMap,
                            transforSitesMap, transforLineMap));
                    break;
            }
            return false;
        }
    });

    private void getAllMetroLine() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("Line", 0);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mProgressDialog.show();
        VolleyUtil.post("GetMetroInfo.do", jsonObject, new VolleyCallBack() {
            @Override
            public void onSucceess(JSONObject jsonObject, String response) {
                MetroInfoBean metroInfoBean = new Gson().fromJson(response, MetroInfoBean.class);
                if (metroInfoBean.getRESULT().equals("S")) {
                    mProgressDialog.cancel();
                    for (MetroInfoBean.ROWSDETAILBean item :
                            metroInfoBean.getROWS_DETAIL()) {
                        ArrayList<String> transforSites = new ArrayList<>();
                        ArrayList<String> allSpot = new ArrayList<>();
                        allSpot.addAll(item.getSites());
                        for (String item1 :
                                item.getTransfersites()) {
                            String s = item1.replaceAll("\r\n", "");
                            transforSites.add(s);
                        }
                        transforSitesMap.put(item.getName(), transforSites);
                        allSpotMap.put(item.getName(), allSpot);
                    }
                    handlerTransforSites();
                }

            }

            @Override
            public void onFailure(String onError) {

            }
        });
    }

    /**
     * @param metroValue 线路名
     * @param type 数据最终送往activity还是dialog
     */
    private void SearchMetroLine(int metroValue, int type) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("Line", metroValue);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mProgressDialog.show();
        VolleyUtil.post("GetMetroInfo.do", jsonObject, new VolleyCallBack() {
            @Override
            public void onSucceess(JSONObject jsonObject, String response) {
                metroInfoBean = new Gson().fromJson(response, MetroInfoBean.class);
                if (metroInfoBean.getRESULT().equals("S")) {
                    mProgressDialog.cancel();
                    if (type == SHOW_ACTIVITY) {
                        Message message = new Message();
                        message.what = 1;
                        handler.sendMessage(message);
                    } else if (type == SHOW_DIALOG) {
                        Message message = new Message();
                        message.what = 2;
                        handler.sendMessage(message);
                    }
                }
            }
                @Override
                public void onFailure (String onError){

                }
            });
        }

    /**
     * 获取站点对应的线路
     */
        private void handlerTransforSites () {

            if (transforSitesMap.isEmpty()) {
                Toast.makeText(this, "网络不通，请重试", Toast.LENGTH_SHORT).show();
            } else {
                Set<Map.Entry<String, List<String>>> entries = transforSitesMap.entrySet();
                //利用hashMap的键会覆盖值存储
                for (Map.Entry<String, List<String>> item :
                        entries) {
                    for (String item1 :
                            item.getValue()) {
                        String s = item1.replaceAll("\r\n", "");
                        if (transforLineMap.containsKey(s)) {
                            List<String> list = transforLineMap.get(s);
                            list.add(item.getKey());
                            transforLineMap.put(s, list);
                        } else {
                            ArrayList<String> strings = new ArrayList<>();
                            strings.add(item.getKey());
                            transforLineMap.put(s, strings);
                        }
                    }
                }

            }

        }

    }
